;(function($){
	
	var citySelector = function($element, config) {
		config = config || {};
		if(!config.inputId)
			config.inputId = $element.attr('id');
		if(!config.hiddenId)
			config.hiddenId = 'hide_' + config.inputId;
		if(!config.id)
			config.id = 'citySelector_'+new Date().getTime();
		
		defaults = citySelector.defaultConfig;
		
		// 合并默认配置
	    for (var i in defaults) {
	        if (config[i] === undefined) {
	            config[i] = defaults[i];
	        };
	    };
		
		return citySelector.list[config.id] = new citySelector.fn.constructor($element, config);
	}
	
	citySelector.list = {};
	$.citySelector = citySelector;
	
	citySelector.fn = citySelector.prototype = {
		constructor: function ($element, config) {
			this.ipt = $element
			this.hide = $('#'+config.hiddenId);
			this.config = config;
			this._lastCheckName = '';
			this._lastCheckValue = 1;
			this.wrapper = $('#'+config.id+'-wrap');
			this.init();
		},
		
		iconReset: function() {
			var config = this.config,
				wrapper = this.wrapper,
				ipt = this.ipt;
			icon = $('.select-pop', wrapper);
			icon.css({
				right: 1 + 'px',
				top: 1 + 'px',
				display: 'block',
				height: '100%'
			}).show();
		},
	
		init: function() {
			this.iconReset();
			var config = this.config, 
				cites = this._formatCites(config.cites),
				$btn = $('.btn-city-input[inputId='+config.inputId+']'),
				domIpt = document.getElementById(config.inputId),
				$dlg = null,
				that = this;
			
			$btn.live('click', function(oEvent) {
				var $dlg = $.dialog({
					id: config.inputId,
					title: 'Top20热门城市（或直接输入城市简拼/全拼）',
					follow: domIpt,
					followPosition: 'left',
					content: cites,
					width: '320px',
					padding: "0 0 10px 10px",
					drag: false
				});
				
				$dlg.dom.content.find('.city-list li').click(function(oEvent) {
					domIpt.value= this.innerHTML;
					that._lastCheckName = domIpt.value;
					$('#'+config.hiddenId).val($(this).attr('value'));
					if($dlg) $dlg.close();
				});
				domIpt.select();
				
				oEvent = oEvent || window.event;
			    if(document.all){
			        oEvent.cancelBubble = true;
			    }else{
			        oEvent.stopPropagation();
			    }
				return false;
			});
			
			$('#'+config.inputId).autocomplete(config.autoComplete.requestUrl, {
				selectFirst: true,
				max: 20,
				scrollHeight: 300,
				width: 200,
				dataType: 'json',
				parse: function(data) {
					return $.map(data, function(row) {
						return {
							data: row,
							value: row.id,
							result: row.name
						}
					});
				},
				formatItem: function(item) {
					return item.pstr+'（'+item.name + "）";
				}
			}).result(function(event, data, formatted) {
				$('#'+config.hiddenId).val(formatted); 
			}).keydown(function() {
				if($dlg = $.dialog.get(config.inputId)) $dlg.close();
			}).blur(function() {
				if(that._lastCheckName != this.value) {
					that.checkValue();
				}
			});
			
			$('body').click(function() {
				if($dlg = $.dialog.get(config.inputId) && $dlg) $dlg.close();
			})
			
		},
		
		checkValue: function(success, fail) {
			
			var config = this.config,
				that = this,
				value = $('#'+config.inputId).val();
			if( !value || (that._lastCheckName == value && $('#'+config.hiddenId).val()) ) {
				if(success) success.call();
				return;
			}
			$.get(config.checkUrl, {name: value}, function(result) {
				that._lastCheckName = value;
				that._lastCheckValue = result;
				$('#'+config.hiddenId).val(result);
				if(!result) {
					if(fail) fail.call();
				} else {
					if(success) success.call();
				}
			})
		},
		
		_formatCites: function(cites) {
			var html = '<ul class="city-list">';
			for(i=0; i<cites.length; ++i) {
				city = cites[i];
				html += '<li ="item-city" value="'+city.id+'">'+city.value+'</li>';
			}
			html += '</ul>';
			return html;
		}
		
	}
	
	citySelector.fn.constructor.prototype = citySelector.fn;
	$.fn.citySelector = function(config) {
		return citySelector(this, config);
	}
	
	$.citySelector.get = function(id) {
		if(id == null) {
			return citySelector.list;
		} else {
			return citySelector.list[id] ? citySelector.list[id] : null;
		}
	}
	
	citySelector.defaultConfig = {}
	
})(jQuery);